package com.ponxu.mb.service;

import com.ponxu.db.SqlBuilder;
import com.ponxu.db.SqlRunner;
import com.ponxu.db.wrap.impl.StringRowWrapper;
import com.ponxu.mb.Global;
import com.ponxu.mb.db.ConnectionManager;
import com.ponxu.utils.Lang;

/**
 * 设置
 * 
 * @author xwz
 */
public class OptionService {
	public static String OPTION_TABLE = Global.read("DB_TABLE_PREFIX")
			+ "option";

	public static String read(String name) {
		SqlRunner runner = new SqlRunner(ConnectionManager.get());

		SqlBuilder.SELECT("val");
		SqlBuilder.FROM(OPTION_TABLE);
		SqlBuilder.WHERE("name=?");

		return runner.selectOne(SqlBuilder.SQL(),
				StringRowWrapper.getInstance(), name);
	}

	public static int readInt(String name) {
		return Integer.parseInt(Lang.defaultString(read(name), "0"));
	}

	public static long readLong(String name) {
		return Long.parseLong(Lang.defaultString(read(name), "0"));
	}

	public static boolean readBoolean(String name) {
		return Lang.convertBoolean(read(name));
	}

	public static void wirte(String name, Object val) {
		String oldVal = read(name);
		SqlRunner runner = new SqlRunner(ConnectionManager.get());
		if (oldVal != null) {
			SqlBuilder.UPDATE(OPTION_TABLE);
			SqlBuilder.SET("val=?");
			SqlBuilder.WHERE("name=?");
			runner.execute(SqlBuilder.SQL(), val, name);
		} else {
			SqlBuilder.INSERT_INTO(OPTION_TABLE);
			SqlBuilder.VALUES("name, val", "?, ?");
			runner.insert(SqlBuilder.SQL(), name, val);
		}
	}
}
